package com.egu.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.egu.mapper.CustomerSourceMapper;
import com.egu.model.CustomerSource;
import com.egu.model.CustomerSourceExample;
import com.egu.model.CustomerSourceExample.Criteria;
import com.egu.service.CustomerSourceService;
import com.egu.vo.PageParam;
import com.egu.vo.RequestPageVo;
import com.egu.vo.RequestResultVo;
@Service
public class CustomerSourceServiceImple implements CustomerSourceService{

	@Autowired
	CustomerSourceMapper customerSourceMapper;

	public RequestPageVo<CustomerSource> getList(PageParam param, CustomerSource customerSource) {
		RequestPageVo<CustomerSource> result = new RequestPageVo<CustomerSource>();
		CustomerSourceExample example = new CustomerSourceExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsUsedEqualTo("1");
		if (StringUtils.isNotBlank(customerSource.getSourceName())) {
			criteria.andSourceNameLike("%" + customerSource.getSourceName() + "%");
		}
		int count = (int) customerSourceMapper.countByExample(example);
		if (count > 0) {
			example.setStartPage(param.getOffset());
			example.setPageSize(param.getLimit());
			List<CustomerSource> list = customerSourceMapper.selectByExample(example);
			result.setRows(list);
			result.setTotal(count);
		}
		return result;
	}

	@Override
	public RequestResultVo<List<CustomerSource>> getAllList() {
		CustomerSourceExample example = new CustomerSourceExample();
		example.createCriteria().andIsUsedEqualTo("1");
		List<CustomerSource> list = customerSourceMapper.selectByExample(example);
		return RequestResultVo.success(list);
	}

	@Override
	@Transactional
	public RequestResultVo<CustomerSource> saveOrUpdate(CustomerSource customerSource) {
		if (customerSource.getId() == null) {
			customerSourceMapper.insertSelective(customerSource);
		} else {
			customerSourceMapper.updateByPrimaryKeySelective(customerSource);
		}
		return RequestResultVo.success();
	}

	@Override
	@Transactional
	public RequestResultVo<CustomerSource> deleteDataById(Integer id) {
		CustomerSource customerSource = new CustomerSource();
		customerSource.setId(id);
		customerSource.setIsUsed("0");
		try {
			customerSourceMapper.updateByPrimaryKeySelective(customerSource);
		} catch (Exception e) {
			return RequestResultVo.error("数据库删除失败");
		}
		return RequestResultVo.success();
	}

}
